package com.worldstear.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.worldstear.core.R;
import com.worldstear.model.FinanceRecord;
import com.worldstear.service.FinanceRecordService;
import com.worldstear.utils.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("finance/record")
@ResponseBody
public class FinanceRecordController {

    final FinanceRecordService financeRecordService;

    public FinanceRecordController(FinanceRecordService financeRecordService) {
        this.financeRecordService = financeRecordService;
    }

    @PostMapping("import/excel")
    public R<Void> importExcel(MultipartFile file) throws Exception {
        if(Objects.isNull(file)) {
            return R.error("文件不能为空");
        }
        List<FinanceRecord> financeRecords =
                ExcelImportUtil.importExcel(FileUtils.saveMultipartFile(file), FinanceRecord.class, new ImportParams());
        financeRecordService.saveBatch(financeRecords);
        return R.success(null);
    }

    @GetMapping
    public R<List<FinanceRecord>> list(Map<String, String> queryParam) {
        FinanceRecord financeRecord = BeanUtils.mapToBean(queryParam, FinanceRecord.class);
        List<FinanceRecord> result = financeRecordService.list(Wrappers.query(financeRecord));
        return R.success(result);
    }
}
